<?php

namespace app\api\repository;

use app\api\model\WeChatMerchant;

/**
 * 微信商户数据仓库类
 */
class WeChatMerchantRepository
{
    private WeChatMerchant $model;

    public function __construct()
    {
        $this->model = new WeChatMerchant();
    }

    /**
     * 根据ID查找商户
     */
    public function findById(int $id): ?array
    {
        $result = $this->model->where('id', $id)->find();
        return $result ? $result->toArray() : null;
    }

    /**
     * 根据条件查找商户
     */
    public function findByCondition(array $where): ?array
    {
        $query = $this->model;
        
        foreach ($where as $field => $value) {
            $query = $query->where($field, $value);
        }
        
        $result = $query->find();
        return $result ? $result->toArray() : null;
    }

    /**
     * 获取分页列表
     */
    public function getPaginatedList(array $where, int $page, int $pageSize): array
    {
        $query = $this->model;
        
        // 构建查询条件
        foreach ($where as $field => $value) {
            if (!empty($value)) {
                $query = $query->where($field, $value);
            }
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取分页数据
        $data = $query->page($page, $pageSize)
                     ->order('id', 'desc')
                     ->select()
                     ->toArray();
        
        return [
            'data' => $data,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize,
        ];
    }

    /**
     * 创建商户
     */
    public function create(array $data): int
    {
        $merchant = $this->model->create($data);
        return $merchant->id;
    }

    /**
     * 更新商户
     */
    public function update(int $id, array $data): bool
    {
        return $this->model->where('id', $id)->update($data) > 0;
    }

    /**
     * 删除商户
     */
    public function delete(int $id): bool
    {
        return $this->model->where('id', $id)->delete() > 0;
    }

    /**
     * 批量更新状态
     */
    public function batchUpdateStatus(array $ids, string $status): int
    {
        return $this->model->whereIn('id', $ids)->update([
            'status' => $status,
            'update_time' => time(),
        ]);
    }

    /**
     * 根据OpenID获取商户列表
     */
    public function getByOpenId(string $openid): array
    {
        return $this->model->where('openid', $openid)
                          ->order('id', 'desc')
                          ->select()
                          ->toArray();
    }

    /**
     * 获取统计数据
     */
    public function getStatistics(string $openid = ''): array
    {
        $query = $this->model;
        
        if (!empty($openid)) {
            $query = $query->where('openid', $openid);
        }
        
        return [
            'total' => $query->count(),
            'draft' => $query->where('status', 'draft')->count(),
            'submitted' => $query->where('status', 'submitted')->count(),
            'approved' => $query->where('status', 'approved')->count(),
            'rejected' => $query->where('status', 'rejected')->count(),
        ];
    }

    /**
     * 搜索商户
     */
    public function search(array $params): array
    {
        $query = $this->model;
        
        // 关键词搜索
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query = $query->where(function ($q) use ($keyword) {
                $q->whereOr('merchant_name', 'like', "%{$keyword}%")
                  ->whereOr('business_license_number', 'like', "%{$keyword}%")
                  ->whereOr('legal_person', 'like', "%{$keyword}%");
            });
        }
        
        // 状态筛选
        if (!empty($params['status'])) {
            $query = $query->where('status', $params['status']);
        }
        
        // 时间范围
        if (!empty($params['start_time'])) {
            $query = $query->where('create_time', '>=', strtotime($params['start_time']));
        }
        
        if (!empty($params['end_time'])) {
            $query = $query->where('create_time', '<=', strtotime($params['end_time']));
        }
        
        // 分页
        $page = $params['page'] ?? 1;
        $pageSize = $params['page_size'] ?? 10;
        
        $total = $query->count();
        $data = $query->page($page, $pageSize)
                     ->order('id', 'desc')
                     ->select()
                     ->toArray();
        
        return [
            'data' => $data,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize,
        ];
    }


    /**
     * 根据ID查找商户
     */
    public function getField(string $id, string $field)
    {
        $result = $this->model->where('id', $id)->field($field)->find();
        return $result ? $result->toArray() : null;
    }
}
